package com.kuaishou.locallife.open.api.common.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

import com.kuaishou.locallife.open.api.KsLocalLifeApiException;

/**
 * @author gaojiapei <gaojiapei@kuaishou.com>
 * Created on 2023-02-05
 */
public class SignUtils {

    /**
     * 服务商签名密钥
     */
    private String signSecret;

    public SignUtils(String signSecret) {
        this.signSecret = signSecret;
    }

    /**
     * @param queryMap URL Query参数
     * @param targetSign 快手侧签名字符串
     * @return 验证签名结果 true 成功 false失败
     * @throws KsLocalLifeApiException
     */
    public boolean verify(Map<String, String> queryMap, String targetSign) throws KsLocalLifeApiException {
        return verify(queryMap, "", targetSign);
    }


    /**
     * @param queryMap URL Query参数
     * @param bodyJson post请求body json串
     * @param targetSign 快手侧签名字符串
     * @return 验证签名结果 true 成功 false失败
     * @throws KsLocalLifeApiException
     */
    public boolean verify(Map<String, String> queryMap, String bodyJson, String targetSign)
            throws KsLocalLifeApiException {
        String signStr = buildSignStr(queryMap, bodyJson);
        String sourceSign = SHAUtils.sha256(signStr);
        return sourceSign.equals(targetSign);
    }

    /**
     * 按照字典升序构建待签名字符串
     * @param queryMap
     * @param bodyJson
     * @return
     */
    public String buildSignStr(Map<String, String> queryMap, String bodyJson) {
        StringBuilder signStr = new StringBuilder();
        signStr.append(this.signSecret);

        if (queryMap != null) {
            if (queryMap.containsKey("sign")) {
                queryMap.remove("sign");
            }
            // query参数字典升序排列
            Set<String> keySet = queryMap.keySet();
            ArrayList<String> keyList = new ArrayList<>(keySet);
            Collections.sort(keyList);

            for (String key : keyList) {
                signStr.append("&");
                signStr.append(key);
                signStr.append("=");
                signStr.append(queryMap.get(key));
            }

        }

        // 如果是post请求
        if (!KsStringUtils.isBlank(bodyJson)) {
            signStr.append("&http_body=");
            signStr.append(bodyJson);
        }
        
        return signStr.toString();
    }

    public String getSignSecret() {
        return signSecret;
    }

    public void setSignSecret(String signSecret) {
        this.signSecret = signSecret;
    }
}
